package com.liu.boot03.config;

import com.liu.boot03.model.User;
import com.liu.boot03.service.UserService;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import javax.annotation.Resource;

//AOP 拦截器
@EnableWebSecurity
@Configuration
public class AuthProviderConfig extends WebSecurityConfigurerAdapter {

    @Resource
    UserService userService;
    //认证
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //首页所有人能访问
        //请求授权规则
        http
                .authorizeRequests()    //所有认证请求
                .antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasRole("vip1")
                .antMatchers("/level2/**").hasRole("vip2")
                .antMatchers("/level3/**").hasRole("vip3");

        //权限不足跳登录   定制登录页
        http.formLogin().loginPage("/toLogin");
        //防止网站工具
        http.csrf().disable();//关闭csrf请求
        //注销
        http.logout().logoutSuccessUrl("/");
        http.rememberMe().rememberMeParameter("rememberme");
    }

    //授权  //AuthenticationManagerBuilder中适配器模式和建造者模式
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        User login = userService.login("", "");

        //定义认证规则(在内存中读取)
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("刘青双").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2","vip3")
                .and().withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
                .and().withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1")

        ;
    }
}
